import LazyLoading from "../../utils/LazyLoading";
import router, { resetRouter, AddRouter } from "../../router";
import layout from "../../layout";
const state = {
  MenuData: [],
  RouterData: []
};
//内部方法 fn:(state, view) => {}
const mutations = {
  SET_MEUNDATA: (state, value) => {
    state.MenuData = value;
  },
  SET_ROUTERDATA: (state, value) => {
    state.RouterData = value;
  }
};
//对外方法 fn({ commit },value)
const actions = {
  setMenuData({ commit, state }, data) {
    return new Promise(resolve => {
      commit("SET_MEUNDATA", data);
      //动态添加路由 //addRoutes {path,name,component}
      router.options.routes.length = 0;
      //判断文件是否存在 不存在不添加
      const modulesFiles = require.context("../../view", true);
      // console.log(modulesFiles.keys());
      let newrouters = [];
      data.forEach(item => {
        //console.log("./" + item.url);
        //console.log(modulesFiles.keys().includes("./" + item.url));
        //let routeritem = { ...item };
        if (item.url && modulesFiles.keys().includes("./" + item.url)) {
          let pitem = data.search({ id: item.pid });
          let meun = Object.assign(
            {},
            {
              path: "/system",
              component: layout,
              redirect: "/" + item.url,
              //component: LazyLoading(item.url),,
              children: [
                {
                  path: "/" + item.url,
                  component: LazyLoading(item.url),
                  name: item.url.split("/")[item.url.split("/").length - 1],
                  meta: {
                    breadcrumb: [pitem[0].text, item.text],
                    activeMenu: item.id.toString()
                  }
                }
              ]
            }
          );
          newrouters.push(meun);
        }
      });
      // resetRouter();
      // console.log(newrouters);
      router.options.routes.push(...newrouters);
      router.addRoutes(newrouters);
      commit("SET_ROUTERDATA", newrouters);
      resolve([newrouters]);
    });
  }
};
const getters = {
  MenuData: state => state.MenuData,
  RouterData: state => state.RouterData
};

/**
 * @description 菜单相关
 */
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
